const { activityDetail, giveLike, disLike } = require('../../api/activity')
const { getCreditWithShare } = require('../../api/user')
const { API_OK } = require('../../utils/setting')
const { debounce } = require('../../utils/util')
const app = getApp()

Page({
  data: {
    image: '',
    name: '',
    detail: '',
    time: '',
    address: '',
    isLike: false,
    likeNumber: 0
  },
  pageData: {
    id: null
  },
  onLoad: function (options) {
    // console.log(options)
    wx.setNavigationBarTitle({ title: options.title })
    this.pageData.id = options.id
  },
  onReady: function () {
    if (wx.getStorageSync('token')){
      this.getDetail()
    } else {
      app.tokenReadyCallback = this.getDetail
      app.getTokenFailedCallback = () => {
        wx.hideLoading()
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    getCreditWithShare()
    return {
      title: this.data.name,
      path: `/pages/activity/activity?id=${this.pageData.id}`
    }
  },
  getDetail() {
    wx.showLoading({ title: '拼命加载中', mask: true })
    activityDetail({
      data: { activity_id: this.pageData.id },
      callback: wx.hideLoading
    })
      .then(res => {
        // console.log(res)
        if (res.code === API_OK) {
          this.setData({
            image: (res.data.images && res.data.images.length) && res.data.images[0].file_path,
            name: res.data.title,
            detail: res.data.content,
            time: res.data.start_end_time,
            address: res.data.address,
            video: res.data.video_url,
            isLike: !!res.data.is_like,
            likeNumber: res.data.likes_count
          })
        }
      })
      .catch(err => {
        console.warn(err)
      })
  },
  toggleGiveLike: debounce(async function() {
    try {
      const res = this.data.isLike ? await disLike({ data: { activity_id: this.pageData.id } }) : await giveLike({ data: { activity_id: this.pageData.id } })

      if (res.code === API_OK) {
        this.setData({ isLike: !this.data.isLike, likeNumber: this.data.isLike ? this.data.likeNumber - 1 : this.data.likeNumber + 1 })
      }
    } catch(err) {
      console.warn(err)
    }
  }, 300)
})
